# 負責管理留言的控制器.
class PostsController < ApplicationController 
  
  # 除了新增,顯示單筆資料外,其它方法都要登入才能使用.
  before_filter :authorize, :except => [:new, :create]
  
  # 只有新增留言外要最愛電報清單 .
  before_filter :find_favorite, :only => [:create, :new]
  
  
  # GET /posts
  # GET /posts.xml
  def index
    @posts = Post.find(:all)

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @posts }
    end
  end

  # GET /posts/1
  # GET /posts/1.xml
  def show
    @post = Post.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @post }
    end
  end

  # GET /posts/new
  # GET /posts/new.xml
  def new
    @post = Post.new
    session[:computer_id] = params[:id] # 將電報編號放入 session .
    put_noisy_image_into_session

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @post }
    end
  end

  # GET /posts/1/edit
  def edit
    @post = Post.find(params[:id])
  end

  # POST /posts
  # POST /posts.xml
  def create
    @post = Post.new(params[:post])
    @post.computer_id = session[:computer_id]
    
    # 驗證圖片數字是否吻合.
    unless params[:typed_code] == session[:noisy_image].code
      flash[:notice] = '驗證碼錯誤'
      redirect_to(:action => :new, :id => @post.computer_id) and return false
    else
      respond_to do |format|
        if @post.save
          flash[:notice] = '留言成功'
          format.html { redirect_to :controller => 'computers', :action => 'show', :id => @post.computer_id }
          format.xml  { render :xml => @post, :status => :created, :location => @post }
        else
          format.html { render :action => :new, :id => @post.computer_id}
          format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }
        end
      end
    end
    
  end

  # PUT /posts/1
  # PUT /posts/1.xml
  def update
    @post = Post.find(params[:id])
    computer_id = @post.computer_id
    
    respond_to do |format|
      if @post.update_attributes(params[:post])
        flash[:notice] = '更新留言成功'
        format.html { redirect_to :controller => 'computers', :action => 'show', :id => computer_id }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /posts/1
  # DELETE /posts/1.xml
  def destroy
    @post = Post.find(params[:id])
    computer_id = @post.computer_id
    @post.destroy

    respond_to do |format|
      format.html { redirect_to :controller => 'computers', :action => 'show', :id => computer_id }
      format.xml  { head :ok }
    end
  end
  
end
